package com.cwh.taskcenter.task.executor.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.cwh.taskcenter.domain.common.LockConstants;
import com.cwh.taskcenter.domain.task.model.Task;
import com.cwh.taskcenter.domain.task.model.UserTask;
import com.cwh.taskcenter.domain.task.gateway.TaskGateWay;
import com.cwh.taskcenter.domain.task.gateway.UserTaskGateWay;
import com.cwh.taskcenter.domain.task.model.UserTaskStatus;
import com.cwh.taskcenter.task.TaskReceiveCmd;
import com.cwh.taskcenter.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReceiveTaskCmdExe {

    @Autowired
    private TaskGateWay taskGateWay;
    
    @Autowired
    private UserTaskGateWay userTaskGateWay;

    @Autowired
    private DistributedLock distributedLock;


    @Transactional(rollbackFor = Exception.class)
    public Response execute(TaskReceiveCmd cmd) {

        String lockKey = LockConstants.LOCK_KEY_TASK_ACCEPTANCE + cmd.getTaskId();
        try {
            boolean lock = distributedLock.tryLock(lockKey, 30, 30, TimeUnit.SECONDS);
            if (!lock) {
                return Response.buildFailure("LOCK_FAILED", "获取锁失败");
            }
            // 检查任务是否存在
            Task task = taskGateWay.getById(cmd.getTaskId());
            if (task == null) {
                throw new BizException("任务不存在");
            }

            // 3.检查任务状态
            task.checkTaskAcceptable();

            // 检查用户是否已领取该任务
            if (userTaskGateWay.isUserTaskAccepted(cmd.getTaskId(), cmd.getUserId())) {
                throw new BizException("已领取该任务");
            }

            // 创建用户任务领域对象
            UserTask userTask = new UserTask();
            userTask.setTaskId(cmd.getTaskId());
            userTask.setUserId(cmd.getUserId());
            userTask.setUserTaskStatus(UserTaskStatus.NOT_STARTED.name());
            userTask.setProgress(0);
            // 保存用户任务
            userTaskGateWay.save(userTask);

        } catch (Exception e) {
            log.error("领取任务失败", e);
            throw new BizException("领取任务失败,请稍后再试");
        }finally {
            distributedLock.unlock(lockKey);
        }
        return Response.buildSuccess();
    }
}